<script setup>
import { defineComponent, ref } from "@vue/runtime-core";
import {useRouter} from "vue-router"
import MyTree from "/components/myTree/MyTree.vue";

let router = useRouter();


// 通过路由获取所有需要展示的侧边栏
// 如果有bar就不给它设置跳转属性--而是打开子节点.
const getPath = function() {
    let ans = [];
    let root = router.getRoutes().filter(v=>{
        if(v.meta && v.meta.root)return true;
        return false;
    })[0];
    let sons =  root.children.slice(1);
    
    const parser = function(node) {
        let bar = {};
        bar.name = node.meta.name;
        bar.icon = node.meta.icon;
        bar.to = node.path;
        bar.select = false;
        if(bar.name === "home" ) {
            bar.select = true;
        }
        bar.son = [];
        node.children = node.children || [];
        for(let x of node.children) {
            bar.son.push(parser(x));
        }
        return bar;
    }

    sons.forEach(v=>{
        ans.push(parser(v))
    })

    return ans;
}

/*
    bar: {
        icon: "",   //如果没有icon表示不需要图标
        name: "",
        to: ""
        son: [...bar]
    }
    shows = [...bar]
*/



// 获取需要展示的侧边属性
const shows = ref(getPath());



// 控制Sider是否pack
import getEventBus from "@utils/eventBus.js";
import {SIDERCHANGE,TAGCHANGE} from "@utils/myConst.js";
const eb = getEventBus();
const packSider = ref(false);
eb.on(SIDERCHANGE,"Sider",(val)=>{
    packSider.value = val;
})

// 检测tag变化
eb.on(TAGCHANGE,"Sider",(tagName)=>{
    const dfs = function(node) {
        if(!node)return ;
        if(node.name === tagName) {
            node.select = true;
        } else {
            node.select = false;
        }
        for(let x of node.son) {
            dfs(x);
        }
    }
    for(let x of shows.value) {
        dfs(x);
    }
})


</script>

<template>
    <div class="scroll-main-container">
        <el-scrollbar wrap-class="sidebar-container">
            <!-- 通过读取路由来递归生成菜单 -->
            <MyTree v-for="item in shows" :key="item.name" :bar="item" :pack="packSider"></MyTree>
        </el-scrollbar>
    </div>
</template>

<style lang="scss">
    @import "@scss/sider/sider.scss";
</style>